package com.itboye.ihomebank.activity.home;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.activity.homefragment.HouseDetailActivity;
import com.itboye.ihomebank.adapter.AreaChildAdapter;
import com.itboye.ihomebank.adapter.ChooseAreaAdapter;
import com.itboye.ihomebank.adapter.HomeAdapter;
import com.itboye.ihomebank.adapter.HuXingAdapter;
import com.itboye.ihomebank.adapter.OrderAdapter;
import com.itboye.ihomebank.adapter.TeSeAdapter;
import com.itboye.ihomebank.adapter.ZuJinAdapter;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.HouseListBean;
import com.itboye.ihomebank.bean.HouseListBeanCopy;
import com.itboye.ihomebank.bean.HouseListBeanCopy.Acreage;
import com.itboye.ihomebank.bean.HouseListBeanCopy.Floor;
import com.itboye.ihomebank.bean.HouseListBeanCopy.HouseItem;
import com.itboye.ihomebank.bean.HouseListBeanCopy.HouseTag;
import com.itboye.ihomebank.bean.HouseListBeanCopy.HouseType;
import com.itboye.ihomebank.bean.HouseListBeanCopy.Order;
import com.itboye.ihomebank.bean.HouseListBeanCopy.Orientation;
import com.itboye.ihomebank.bean.HouseListBeanCopy.RentType;
import com.itboye.ihomebank.bean.HouseListBeanCopy.Rental;
import com.itboye.ihomebank.bean.HouseListBeanCopy.Source;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.SouSuoBean;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.custom.XListView;
import com.itboye.ihomebank.custom.XListView.IXListViewListener;
import com.itboye.ihomebank.db.DBManager;
import com.itboye.ihomebank.presenter.HousePresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.liandong.DoubleListPopViewUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * 首页的搜索
 * 
 */
public class ActivityHomeSouSuo extends BaseOtherActivity implements Observer,
		OnItemClickListener, IXListViewListener {
	View v_statusbar;
	private ImageView sousuo_finish;// 返回
	private EditText sousuo_txt;;// 输入搜索内容
	private ImageView sousuo_dingwei;;// 定位
	private LinearLayout sousuo_weizhi, sousuo_zujin, sousuo_paixu,
			sousuo_gengduo;

	private XListView sousuo_listview;
	LinearLayout main;
	HomeAdapter adapter;
	private List<SouSuoBean> arrayLists = new ArrayList<>();
	HousePresenter housePresenter;
	PopupWindow popupWindow;
	private SQLiteDatabase database;

	private String cityCode;
	private String city;
	private DBManager dbManager;
	private LinearLayout layout;
	private ListView rootList;
	private FrameLayout flChild;
	private ListView childList;
	private PopupWindow mPopWin;
	List<HouseListBeanCopy.HouseItem> arrayArea = new ArrayList<HouseListBeanCopy.HouseItem>();
	List<HouseListBeanCopy.HouseItem.InnerItem> innerItemsArray = new ArrayList<HouseListBeanCopy.HouseItem.InnerItem>();
	List<HouseItem> area = new ArrayList<HouseListBeanCopy.HouseItem>();
	List<Rental> rental = new ArrayList<HouseListBeanCopy.Rental>();
	List<Acreage> acreage = new ArrayList<HouseListBeanCopy.Acreage>();
	List<HouseType> houseType = new ArrayList<HouseListBeanCopy.HouseType>();
	List<RentType> rentType = new ArrayList<HouseListBeanCopy.RentType>();
	List<Orientation> orientation = new ArrayList<HouseListBeanCopy.Orientation>();
	List<Floor> floor = new ArrayList<HouseListBeanCopy.Floor>();
	List<Source> source = new ArrayList<HouseListBeanCopy.Source>();
	List<HouseTag> houseTag = new ArrayList<HouseListBeanCopy.HouseTag>();
	List<Order> order = new ArrayList<HouseListBeanCopy.Order>();
	private GridView gridView;
	private GridView guigeContainer2;
	private HuXingAdapter huXingAdapter;
	private TeSeAdapter teseAdapter;
	TextView no_data;
	/**
	 * cityCode 城市code searchText 查询文本 areaOrZone 为空不限,区或区域 rental 为空不限,租金
	 * 自定义查询规则 brp:大于等于多少 erp:小于等于多少 例如 brp100erp200 大于等于100小于等于200
	 * aceage为空不限,面积 rba:大于等于多少 rea:小于等于多少 例如 rba100rea200 大于等于100小于等于200
	 * houseType为空不限,房型 rentType 租房类型 decoration 为空不限,装修 oritation 为空不限,朝向 floor
	 * 为空不限,楼层 source 为空不限,房源 用来查找（个人，经纪人） houseTag order 为空不限,排序 perPage
	 * 每页条数，默认10条一页 currentPage 页码，默认第一页
	 */
	protected String areaOrZone = "";
	protected String searchText= "";
	protected String aceage = "";
	protected String rentalMoney = "";
	protected String house_tag = "";
	protected int pageNo = 1;
	protected String orderType = "";
	protected String house_type = "";
	String uid;
	TextView li_history_search,hot_search;
	private ArrayList<com.itboye.ihomebank.bean.HouseListBean.HouseItem> houseItems;


	private DoubleListPopViewUtil areaPopupWindow;

	@Override
	protected int layout_id() {
		return R.layout.activity_home_sousuo;
	}

	@Override
	protected void onInit() {
		setStatusBarHeight(v_statusbar);
		li_history_search.setVisibility(View.GONE);
		hot_search.setVisibility(View.GONE);
		showProgressDialog("正在努力搜索,请稍后...", false);
		sousuo_dingwei.setVisibility(View.GONE);
		houseItems = new ArrayList<com.itboye.ihomebank.bean.HouseListBean.HouseItem>();
		adapter = new HomeAdapter(ActivityHomeSouSuo.this,
				houseItems);
		sousuo_listview.setAdapter(adapter);
		uid=SPUtils.get(this, null, SPContants.USER_ID, "")+"";
		sousuo_listview.setAdapter(adapter);
		searchText = getIntent().getStringExtra("hot");
		sousuo_txt.setText(searchText);
		dbManager = new DBManager(this);
		dbManager.openDateBase();
		dbManager.closeDateBase();
		database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/"
				+ DBManager.DB_NAME, null);
		city = SPUtils.get(this, null, SPContants.SELECT_CITY, "") + "";
		if (city != null) {
			cityCode = getCityCode(city);
			housePresenter.queryHouse(cityCode, sousuo_txt.getText().toString().trim(), areaOrZone,
					rentalMoney, "", house_type, "", "", "", "", "", house_tag,
					orderType, "10", pageNo + "",uid);
		}

		popupWindow = new PopupWindow();

		sousuo_listview.setXListViewListener(this);
		sousuo_listview.setPullLoadEnable(true);
		sousuo_listview.setPullRefreshEnable(true);
		sousuo_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				if (houseListBean == null) {
					ByAlert.alert("数据有误,请查看网络...");
					return;
				}
				if (houseItems.size() <= 0) {
					ByAlert.alert("数据有误,请查看网络...");
					return;
				}
				String uid = SPUtils.get(ActivityHomeSouSuo.this, null,
						SPContants.USER_ID, "") + "";
				Intent intent = new Intent(ActivityHomeSouSuo.this,
						HouseDetailActivity.class);
				intent.putExtra("uid", uid);
				intent.putExtra("house_no", houseItems.get(position - 1)
						.getHouseNo());
				startActivity(intent);
			}
		});
		sousuo_txt
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					public boolean onEditorAction(TextView v, int actionId,
							KeyEvent event) {
						if (sousuo_txt.getText().toString().equals("")) {
							ByAlert.alert("请输入搜索关键词");
							return false;
						}
						if (actionId == EditorInfo.IME_ACTION_SEARCH
								|| (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
						String	searchTexts = sousuo_txt.getText().toString();
							housePresenter.queryHouse(cityCode, searchTexts,
									areaOrZone, rentalMoney, "", house_type,
									"", "", "", "", "", house_tag, orderType,
									"10", pageNo + "",uid);
							return true;
						}
						return false;
					}
				});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.sousuo_finish:
			finish();
			break;
		case R.id.sousuo_txt:// 输入内容

			break;
		case R.id.sousuo_dingwei:// 定位
			String ssearchText = sousuo_txt.getText().toString();
			if (ssearchText.equals("")) {
				ByAlert.alert(getString(R.string.msg));
				return;
			}
			housePresenter.queryHouse(cityCode, ssearchText, "", "", "", "", "",
					"", "", "", "", "", "", "", "",uid);
			break;
		case R.id.sousuo_weizhi:// 位置
			//	showPopupWindow(main.getWidth(), main.getHeight());
				showAreaPopBtn();
			break;
		case R.id.sousuo_zujin:// 租金
			PuPoZuJin(v);

			break;
		case R.id.sousuo_paixu:// 排序
			PuPoPaiXu(v);

			break;
		case R.id.sousuo_gengduo:// 更多
			PuPoGengDuo(v);
			break;
		default:
			break;
		}

	}

	private String getCityCode(String city) {
		// TODO Auto-generated method stub
		Cursor cursor = null;
		if (database != null)
			cursor = database.query("hat_city", new String[] { "cityID" },
					"city=?", new String[] { city.equals("") ? "杭州市" : city },
					null, null, null);
		if (cursor != null) {
			while (cursor.moveToNext()) {
				cityCode = cursor.getString(0);
			}
			cursor.close();
		}
		if (database != null) {
			database.close();
		}
		Log.v("cityId", cityCode + "---------------" + city);
		if (cityCode != null) {
			getListViewData(cityCode);
		}
		return cityCode;
	}

	private void getArea(String cityCode) {
		// TODO Auto-generated method stub
		database = dbManager.openDateBase();
		Cursor cursor = null;
		if (database != null)
			cursor = database.query("hat_area", null, "father=?",
					new String[] { cityCode }, null, null, null);
		if (cursor != null) {
			while (cursor.moveToNext()) {
				// itemList.add(cursor.getString(cursor
				// .getColumnIndexOrThrow("area")));
			}
			cursor.close();
		}
	}

	@Override
	protected void onInitController() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onReadIntent(Bundle bundle) {
		// TODO Auto-generated method stub

	}

	private void getListViewData(String cityCode) {
		housePresenter = new HousePresenter(this);
		housePresenter.getAreaByCityCode(cityCode);
	}
	private int selectedPosition;//根目录被选中的节点
	/**
	 * 地区选择的popupwindow
	 */
	private void showAreaPopBtn() {
		areaPopupWindow = new DoubleListPopViewUtil(this, sousuo_weizhi, oneList, twoList) {
			@Override
			public void onRootListviewOnClick(View v, int position) {
				selectedPosition = position;
			}

			@Override
			public void onSubListviewOnClick(View v, int position) {
				pageNo = 1;
				areaOrZone = threeList.get(selectedPosition).get(position);
				if (!areaOrZone.equals("")&&threeList.size()>0 ){
					housePresenter
							.queryHouse(cityCode, sousuo_txt.getText().toString().trim(),
									areaOrZone, rentalMoney, "",
									house_type, "", "", "", "", "",
									house_tag, orderType, "10",
									pageNo + "",uid);
					//ByAlert.alert(threeList.get(selectedPosition).get(position));
					areaPopupWindow.dismiss();
				}

			}
		};
		areaPopupWindow.show();
	}
	/**
	 * 位置
	 * 
	 * @param width
	 * @param height
	 */
	private void showPopupWindow(int width, int height) {

		layout = (LinearLayout) LayoutInflater.from(ActivityHomeSouSuo.this)
				.inflate(R.layout.popup_choose_area, null);
		rootList = (ListView) layout.findViewById(R.id.rootcategory);
		if (arrayArea != null) {
			if (arrayArea.size() > 0) {
				ChooseAreaAdapter cla = new ChooseAreaAdapter(
						ActivityHomeSouSuo.this, arrayArea);
				rootList.setAdapter(cla);
				flChild = (FrameLayout) layout.findViewById(R.id.child_lay);
				childList = (ListView) layout.findViewById(R.id.childcategory);
				childList.setAdapter(cla);
				flChild.setVisibility(View.INVISIBLE);// 还占空位，导致点击事件出现bug
				mPopWin = new PopupWindow(layout,
						ViewGroup.LayoutParams.MATCH_PARENT,
						ViewGroup.LayoutParams.WRAP_CONTENT, true);
				mPopWin.setBackgroundDrawable(new BitmapDrawable());
				mPopWin.showAsDropDown(sousuo_weizhi, 5, 1);
				mPopWin.update();

				rootList.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						if (arrayArea != null) {

							if (arrayArea.size() > 0) {
								innerItemsArray = arrayArea.get(position)
										.getAreaZone();
								if (innerItemsArray.size() > 0) {

									flChild.setVisibility(View.VISIBLE);
									AreaChildAdapter childAdapter = new AreaChildAdapter(
											ActivityHomeSouSuo.this,
											innerItemsArray);
									childList.setAdapter(childAdapter);
								} else {
									flChild.setVisibility(View.INVISIBLE);
								}
								//
							}
						}
					}
				});
				childList.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						// TODO Auto-generated method stub
						areaOrZone = innerItemsArray.get(position).getValue();
						if (innerItemsArray != null) {
							if (innerItemsArray.size() > 0) {
								mPopWin.dismiss();
								pageNo = 1;
								housePresenter
										.queryHouse(cityCode, sousuo_txt.getText().toString().trim(),
												areaOrZone, rentalMoney, "",
												house_type, "", "", "", "", "",
												house_tag, orderType, "10",
												pageNo + "",uid);
							}
						}
					}
				});
			}
		}
	}

	/**
	 * 租金的弹出框
	 * @param v
	 */
	private void PuPoZuJin(View v) {
		View view = LayoutInflater.from(this).inflate(R.layout.pop_zujin, null);
		ListView listView = (ListView) view.findViewById(R.id.listView);
		listView.setAdapter(new ZuJinAdapter(this, rental,
				R.layout.item_simple_list));
		popupWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.showAsDropDown(v);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				popupWindow.dismiss();
				pageNo = 1;
				Rental rentalBean = rental.get(position);
				rentalMoney = rentalBean.getValue();
				housePresenter.queryHouse(cityCode, sousuo_txt.getText().toString().trim(), areaOrZone,
						rentalMoney, aceage, house_type, "", "", "", "", "",
						house_tag, orderType, "10", pageNo + "",uid);
			}
		});
	}

	/**
	 * 排序
	 * @param v
	 */
	private void PuPoPaiXu(View v) {
		View view = LayoutInflater.from(this).inflate(R.layout.pop_zujin, null);
		ListView listView = (ListView) view.findViewById(R.id.listView);
		listView.setAdapter(new OrderAdapter(this, order,
				R.layout.item_simple_list));
		popupWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				popupWindow.dismiss();
				orderType = order.get(position).getValue();
				pageNo = 1;

				housePresenter.queryHouse(cityCode, sousuo_txt.getText().toString().trim(), areaOrZone,
						rentalMoney, "", house_type, "", "", "", "", "",
						house_tag, orderType, "010", pageNo + "",uid);
			}
		});
		popupWindow.setOutsideTouchable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.showAsDropDown(v);
	}

	/**
	 * 更多
	 * 
	 * @param v
	 */
	private void PuPoGengDuo(View v) {
		View view = LayoutInflater.from(this).inflate(R.layout.pop_gengduo,
				null);
		TextView ok = (TextView) view.findViewById(R.id.ok);
		TextView reset = (TextView) view.findViewById(R.id.reset);
		gridView = (GridView) view.findViewById(R.id.guigeContainer);
		guigeContainer2 = (GridView) view.findViewById(R.id.guigeContainer2);
		gridView.setAdapter(new HuXingAdapter(this, houseType,
				R.layout.item_other_simple_list));
		huXingAdapter = new HuXingAdapter(this, houseType, R.layout.item_huxing);
		gridView.setAdapter(huXingAdapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				HouseType houseTagbean = houseType.get(position);
				huXingAdapter.setCurrentItem(position);
				house_type = houseTagbean.getValue();
			}
		});
		reset.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				house_tag = "";
				house_type = "";
				huXingAdapter.setCurrentItem(-1);
				teseAdapter.setCurrentItem(-1);
			}
		});
		ok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				popupWindow.dismiss();
				housePresenter.queryHouse(cityCode, sousuo_txt.getText().toString().trim(), areaOrZone,
						rentalMoney, "", house_type, "", "", "", "", "",
						house_tag, orderType, "10", pageNo + "",uid);
			}
		});
		teseAdapter = new TeSeAdapter(this, houseTag, R.layout.item_huxing);
		guigeContainer2.setAdapter(teseAdapter);
		guigeContainer2.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				HouseTag houseTagbean = houseTag.get(position);
				house_tag = houseTagbean.getValue();
				teseAdapter.setCurrentItem(position);
			}
		});
		popupWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.showAsDropDown(v);
	}

	private HouseListBean houseListBean;
	private List<String> oneList=new ArrayList<>();//根目录的节点
	private List<List<String>> twoList=new ArrayList<>();// 子目录节点
	private List<List<String>> threeList=new ArrayList<>();// 子目录节点
	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == HousePresenter.queryHouse_success) {
				houseListBean = (HouseListBean) entity.getData();
				if (houseListBean == null) {
					no_data.setVisibility(View.VISIBLE);
					sousuo_listview.setVisibility(View.GONE);
					return;
				}
				if (pageNo == 1) {
					houseItems.clear();
				}
				houseItems.addAll(houseListBean.getData());
				if (houseItems.size() <= 0) {
					no_data.setVisibility(View.VISIBLE);
					sousuo_listview.setVisibility(View.GONE);
					return;
				}
				no_data.setVisibility(View.GONE);
				sousuo_listview.setVisibility(View.VISIBLE);
				
				adapter.notifyDataSetChanged();
				try {
					stopLoad();
				} catch (Exception e) {
					// TODO: handle exception
				}
				// adapter.notifyDataSetChanged();
			} else if (entity.getEventType() == HousePresenter.queryHouse_fail) {
				try {
					stopLoad();
				} catch (Exception e) {
					// TODO: handle exception
				}
				ByAlert.alert(entity.getData());
			} else if (entity.getEventType() == HousePresenter.queryHouseArea_success) {
				HouseListBeanCopy beanCopy = (HouseListBeanCopy) entity
						.getData();
				if (beanCopy != null) {
					for (int i = 0; i < beanCopy.getArea().size(); i++) {
						oneList.add(beanCopy.getArea().get(i).getName());
						List<String> temp = new ArrayList<>();
						List<String> temp01 = new ArrayList<>();
						for (int i1 = 0; i1 < beanCopy.getArea().get(i).getAreaZone().size(); i1++) {
							temp.add(beanCopy.getArea().get(i).getAreaZone().get(i1).getName());
							temp01.add(beanCopy.getArea().get(i).getAreaZone().get(i1).getValue());
						}
						twoList.add(temp);
						threeList.add(temp01);
					}

					arrayArea.addAll(beanCopy.getArea());
					rental.addAll(beanCopy.getRental());
					acreage.addAll(beanCopy.getAcreage());
					houseType.addAll(beanCopy.getHouseType());
					rentType.addAll(beanCopy.getRentType());
					orientation.addAll(beanCopy.getOrientation());
					floor.addAll(beanCopy.getFloor());
					source.addAll(beanCopy.getSource());
					houseTag.addAll(beanCopy.getHouseTag());
					order.addAll(beanCopy.getOrder());
				}
			} else if (entity.getEventType() == HousePresenter.queryHouseArea_fail) {
				ByAlert.alert(entity.getData());
			}
		}
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		switch (parent.getId()) {
		case R.id.listView:

			break;

		default:
			break;
		}
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		pageNo = 1;
		housePresenter.queryHouse(cityCode, sousuo_txt.getText().toString().trim(), areaOrZone,
				rentalMoney, "", house_type, "", "", "", "", "", house_tag,
				orderType, "10", pageNo + "",uid);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		pageNo++;
		housePresenter.queryHouse(cityCode, sousuo_txt.getText().toString().trim(), areaOrZone,
				rentalMoney, "", house_type, "", "", "", "", "", house_tag,
				orderType, "10", pageNo + "",uid);
	}

	public void stopLoad() {
		sousuo_listview.stopLoadMore();
		sousuo_listview.stopRefresh();
	}

}
